<template>
    <view>
        <!-- gc_school/pages/shop/addgoods.wxml -->
        <cu-custom bgColor="bgmain" :isBack="true">
            <view slot="content">商品管理</view>
        </cu-custom>

        <view class="box">
            <view class="flex align-center text-bold">
                <!-- <text class="cuIcon-more"></text> -->
                <view class="text-red text-xxl">*</view>
                <view class="text-lg">商品信息</view>
            </view>
            <view class="name text-lg margin-top">名称</view>
            <view style="position: relative">
                <textarea class="textarea" :maxlength="maxTextLen" :value="name" @input="textarea" placeholder-style="color:#D1D1D1;" placeholder="请输入名称"></textarea>
                <view class="left_num">{{ word_num }}/{{ maxTextLen }}</view>
            </view>

            <view class="flex justify-between size30 margin-top align-center">
                <view>商品分类</view>
                <picker @change="PickerChange" :value="cate_index" :range="cate" range-key="goods_type_name">
                    <view class="picker text-gray">
                        {{ cate[cate_index].goods_type_name ? cate[cate_index].goods_type_name : '选择分类' }}
                        <text class="cuIcon-right"></text>
                    </view>
                </picker>
            </view>
            <view class="flex size30 margin-top align-center">
                <view>规格设置</view>
                <view class="row" style="margin-left:auto;">
                    <!-- <view class="add addAttr"  @click="showAdd('attributeName')" v-if="!attributeName">添加属性</view> -->
                    <view class="add margin-left" @click="showAdd('specsName')" v-if="!specsName">添加基础规格</view>
                </view>

            </view>
            <view class="justify-between size30 margin-top align-center" v-if="specsName">
                <view class="row">{{specsName}}
                     <image
                        class="edit"
                        src="/static/icon/specs/edit.png"
                        mode="scaleToFill"
                        @click="showAdd('specsName')"
                    />

                     <image
                        class="del"
                        src="/static/icon/specs/del.png"
                        mode="scaleToFill"
                        @click="delAll('specs')"
                    />
                </view>
                <view class="specs row ">
                    <block v-for="(item,index) in specs" :key="index">
                        <view class="item row margin-right margin-top">
                            <view class="type">{{item.type}}</view>
                            <view class="price row">{{item.price}}</view>
                            <image
                                class="close"
                                src="/static/icon/specs/close.png"
                                mode="scaleToFill"
                                @click="del('specs',index)"
                            />
                        </view>
                    </block>
                    <view class="adds row margin-top" @click="showAdd('specs')">
                        <view class="cuIcon-add"></view>
                    </view>
                </view>

            </view>
            <view class="justify-between size30 margin-top align-center" v-if="attributeName">
                <view class="row">{{attributeName}}
                    <image
                        class="edit"
                        src="/static/icon/specs/edit.png"
                        mode="scaleToFill"
                        @click="showAdd('attributeName')"
                    />

                     <image
                        class="del"
                        src="/static/icon/specs/del.png"
                        mode="scaleToFill"
                        @click="delAll('attribute')"
                    />
                </view>
                 
                <view class="specs row ">
                    <block v-for="(item,index) in attribute" :key="index">
                        <view class="item row margin-right margin-top">
                            <view class="type">{{item}}</view>
                            <!-- <view class="price row">{{item.price}}</view> -->
                            <image
                                class="close"
                                src="/static/icon/specs/close.png"
                                mode="scaleToFill"
                                @click="del('attribute',index)"
                            />
                        </view>
                    </block>
                    <view class="adds row margin-top" @click="showAdd('attribute')">
                        <view class="cuIcon-add"></view>
                    </view>
                </view>
            </view>
            <view class="flex size30 margin-top align-center">
                <view>多规格</view>
                <view class="row" style="margin-left:auto;">
                    <!-- <view class="add addAttr" @click="showAdd('attributeName')" v-if="!attributeName">添加属性</view> -->
                    <view class="add margin-left" @click="showAdd('specsListKey')" >添加多规格</view>
                </view>
            </view>

            <block v-for="(item,sindex) in specs_list" :key="sindex">
                <view class="justify-between size30 margin-top align-center">
                    <view class="row">{{item.name}}

                        <image class="edit" src="/static/icon/specs/edit.png" mode="scaleToFill" @click="showAdd('specsListKey',sindex)" />
                        <image class="del" src="/static/icon/specs/del.png" mode="scaleToFill" @click="delAll('specsListKey',sindex)" />
                    </view>
                    <view class="specs row ">
                        <block v-for="(items,index) in item.list" :key="index">
                            <view class="item row margin-right margin-top">
                                <view class="type">{{items.type}}</view>
                                <view class="price row">+{{items.price}}</view>
                                <image class="close" src="/static/icon/specs/close.png" mode="scaleToFill"
                                    @click="del('specss',index,sindex)" />
                            </view>
                        </block>
                        <view class="adds row margin-top" @click="showAdd('specss',sindex)">
                            <view class="cuIcon-add"></view>
                        </view>
                    </view>
                
                </view>
            
            </block>








            <view class="flex justify-between size30 margin-top align-center">
                <view>商品价格</view>
                <input class="name_input text-right" :value="price" @input="priceFun" placeholder-style="color:#D1D1D1;" placeholder="请输入价格" type="digit" />
            </view>
            <view class="flex justify-between size30 margin-top align-center">
                <view>商品库存</view>
                <input class="name_input text-right" v-model="stock"  placeholder-style="color:#D1D1D1;"
                    placeholder="请输入库存" type="number" />
            </view>
            <view class="flex justify-between size30 margin-top align-center">
                <view>限购数量</view>
                <input class="name_input text-right" v-model="quota" placeholder-style="color:#D1D1D1;" placeholder="请输入商品限购数量，0或不填为不限制"
                    type="number" />
            </view>

            
            <view class="size30 margin-top">商品图片</view>
            <image @tap="choose" class="img" :src="img ? img : '/static/images/article/add.png'"></image>
        </view>

        <view class="flex btn_row justify-between">
            <view @tap="submit" data-status="2" class="btn_">存为草稿</view>
            <view @tap="submit" data-status="1" class="btn_">发布上架</view>
        </view>

<!-- =='addSpecs' -->
        <view class="cu-modal" :class="modalName?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">
                        <block v-if="modalName=='specsName'">规格名称</block>
                        <block v-if="modalName=='specs'">商品规格</block>
                        <block v-if="modalName=='attributeName'">属性名称</block>
                        <block v-if="modalName=='attribute'">商品属性</block>
                        <block v-if="modalName=='specsListKey'">规格名称</block>
                        <block v-if="modalName=='specss'">多规格属性</block>
                    </view>
					<view class="action" @tap="close">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="addModal">
                    <view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='specsName'">
                        <view class="key">规格名称</view>
                        <input class="val" v-model="specsName"  placeholder="请输入规格值"  />
                    </view>

					<view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='specs'" >
                        <view class="key">规格值</view>
                        <input class="val" v-model="formData.type"  placeholder="请输入规格值"  />
                    </view>
                    <view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='specs'">
                         <view class="key">价格</view>
                        <input class="val"  v-model="formData.price" type="digit" placeholder="请输入价格"  />
                    </view>
                    
                    <view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='attributeName'">
                        <view class="key">属性名称</view>
                        <input class="val" v-model="attributeName"  placeholder="请输入属性名称"  />
                    </view>
                    <view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='attribute'" >
                        <view class="key">属性值</view>
                        <input class="val" v-model="formData.type"  placeholder="请输入属性值"  />
                    </view>
                    <!-- <view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='attribute'">
                        <view class="key">属性金额</view>
                        <input class="val" v-model="formData.price" placeholder="请输入属性金额" />
                    </view> -->

                    <view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='specsListKey'">
                        <view class="key">规格名称</view>
                        <input class="val" v-model="formData.type" placeholder="请输入属性名称" />
                    </view>

                    <view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='specss'">
                        <view class="key">规格值</view>
                        <input class="val" v-model="formData.type" placeholder="请输入规格值" />
                    </view>
                    <view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='specss'">
                        <view class="key">价格</view>
                        <input class="val" v-model="formData.price" type="digit" placeholder="请输入价格" />
                    </view>




                    <view class="tips row padding-left" v-if="modalName=='specsName'">温馨提醒：基础规格为产品的基础价格，例如:大、中、小碗</view>
                    <view class="tips row padding-left" v-show="modalName=='attributeName'">温馨提醒： 属性不影响价格</view>
                    <view class="tips row padding-left" v-show="modalName=='specsListKey'">温馨提醒： 多规格为基础规格额外的规格例如：可乐、加面、加某种佐料</view>

                    
				</view>
                <view class="cu-bar bg-white">
					<view class="action btns">
						<button class="cu-btn close" @tap="close">取消</button>
						<button class="cu-btn enter" @tap="addSpecs">确定</button>
					</view>
				</view>
			</view>
		</view>


     </view>
</template>

<script>
// gc_school/pages/shop/addgoods.js
import siteInfo from '@/siteinfo.js';
// import list from '../../../unpackage/dist/dev/mp-weixin/gc_school/pages/canteen/list';
var app = getApp();
export default {
    data() {
        return {
            word_num: 0,
            maxTextLen: 20,
            cate: [],
            cate_index: 0,
            img: '',
            name: '',
            price: '',
            cate_id: 0,
            id: 0,
            word_left: '',
            modalName:'',
            formData: {
               
            },
            specs:[
                // {type:"大份", price:"20"},
                // {type:"中份", price:"18"},
                // {type:"小份", price:"15"}
            ],
            specsName:"",
            attribute:[
                // "微辣","不辣"
            ],
            attributeName:"",
            stock:"",
            quota:"",
            specs_list:[],
            si:-1

        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        // this.getCate();

        if (options.id) {
            this.setData({
                id: options.id
            });
            this.getInfo();
        }else{
            this.getCate()

        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    // onShareAppMessage: function () {
    // }
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */ 
    methods: {
        showAdd(name,si=-1){
            if (name == "specsListKey" && this.specs.length==0) {
                this.tips.error("请先添加基础规格")
                return false
            }


            this.modalName=name
            this.si=si
            // specsListKey
            // console.log(this.specs_list[si].name);
            try {
                if (this.specs_list[si].name && name == "specsListKey") {
                    this.formData = {
                        type: this.specs_list[si].name
                    }
                }
            } catch (error) {
                
            }
           
        },

         close(){
            this.modalName=""
             this.formData = {
                 type: "",
                 price: ""
             }
            // setTimeout(() => {
            //     this.formData={
            //         type:"",
            //         price:""
            //     }
            // },1500);
            
         },
         del(type="",index,sindex=-1){

            if (sindex>-1) {
                let item = this.specs_list[sindex]
                item.list.splice(index,1)
                console.log(item);
                this.specs_list[sindex] = item
            }else{
                this[type].splice(index, 1)

            }
         },

        delAll(type,i=-1){
            if (type =="specsListKey") {
                this.specs_list.splice(i,1)
            }else{
                this[type + "Name"] = ''
                this[type] = []
            }
        },
        addSpecs(){
             switch (this.modalName) {
                case "specs":
                    if (!this.formData.type) {
                        this.tips.error("规格值不能为空") 
                        break;
                    }
                    if (!this.formData.price) {
                        this.tips.error("规格价格不能为空") 
                        break;
                    }
                    if (!isFinite(this.formData.price)) {
                        this.tips.error("请输入有效价格") 
                        break;

                    }
                    this.formData.price = Number(this.formData.price).toFixed(2);
                    this[this.modalName].push(this.formData)
                    this.close()

                    break;
                case "attribute":
                    if (!this.formData.type) {
                        this.tips.error("属性值不能为空") 
                        break;
                    }
                    // this[this.modalName].push(this.formData)
                     this[this.modalName].push(this.formData.type)
                    this.close()

                     break;
                case "specsListKey":
                    //  if (!this.formData.type) {
                    //      this.tips.error("属性值不能为空")
                    //      break;
                    //  }
                     if (this.si>-1) {
                         this.specs_list[this.si].name = this.formData.type
                    } else {
                         this.specs_list.push({
                             name: this.formData.type,
                             list: []
                         })
                    }
                    
                    //  this[this.modalName].push(this.formData)
                     this.close()

                     break;
                case "specss":
                     if (!this.formData.type) {
                         this.tips.error("规格值不能为空")
                         break;
                     }
                     if (!this.formData.price) {
                         this.tips.error("规格价格不能为空")
                         break;
                     }
                     if (!isFinite(this.formData.price)) {
                         this.tips.error("请输入有效价格")
                         break;

                     }
                     this.formData.price = Number(this.formData.price).toFixed(2);

                     this.specs_list[this.si].list = [
                         ... this.specs_list[this.si].list,
                         this.formData
                     ]
                     console.log(this.specs_list);
                     this.close()

                     break;

                    
                default:
                    this.close()

                     break;

             }
            
          
             
         },
        getInfo() {
            var that = this;
            app.globalData.util.request({
                url: 'ZhGoods/view',
				method: 'GET',
                data: {
                    id: that.id,
					s_id: uni.getStorageSync('schoolId')
                },

                success(res) {
                    console.log(res.data.data);
                    that.setData({
                        name: res.data.data.goods_name,
                        price: res.data.data.price,
                        img: res.data.data.goods_img,
                        cate_id: res.data.data.goods_type_id,
                        word_num: res.data.data.goods_name.length,
                        stock: res.data.data.stock,
                        quota: res.data.data.quota,
                    });
                    try {
                        that.specs = JSON.parse(res.data.data.specs).list || []
                        that.specsName = JSON.parse(res.data.data.specs).name || ""
                        that.attribute = JSON.parse(res.data.data.attribute).list || []
                        that.attributeName = JSON.parse(res.data.data.attribute).name || ""


                    } catch (error) {
                        
                    }
                        // that.specs =  []

                    try {
                        that.specs_list=JSON.parse(res.data.data.specs_list)  
                    } catch (error) {
                        that.specs_list =[]
                    }
                   
                    that.getCate()
                    
                }
            },true);
        },

        getCate() {
            var that = this;
            app.globalData.util.request({
                url: 'ZhGoodsType/index',
				method: 'GET',
                data: {
                    s_id: uni.getStorageSync('schoolId')
                },

                success(res) {
                    that.cate = res.data.data.list
                    // that.cate_id = res.data.data.list[0].goods_type_id
                    for (var i = 0; i < res.data.data.list.length; i++) {
                        if (res.data.data.list[i].goods_type_id == that.cate_id) {
                            that.setData({
                                cate_index: i
                            });
                        }
                    }
                }
            },true);
        },

        //分类选择
        PickerChange(e) {
            this.setData({
                cate_index: e.detail.value,
                cate_id: this.cate[e.detail.value].goods_type_id
            });
        },

        //图片上传
        choose() {
           var that = this;
           uni.chooseImage({
               count: 1,
               success(res) {
				   console.log(res)
                   that.uploadimg(res.tempFilePaths, 'ImgPost'); // wx.hideLoading({})
               }
           });
        },
        
        
        uploadimg: function (data, method, type) {
			console.log(data)
            uni.showLoading({
                title: '上传中...',
                mask: true
            });
            var that = this; // var count = that.data.addedCount + data.length;
            var count = that.addedCount;
            // for (var i = 0; i < data.length; i++) {
                uni.uploadFile({
                    url: siteInfo.url+'Base/upload',
                    filePath: data[0],
                    header:{
                    	'Authorization':uni.getStorageSync('token')
                    },
                    name: 'file',
                    formData: {
                    	'wxapp_id':siteInfo.uniacid
                    },
                    success: (resp) => {
                        var pic = JSON.parse(resp.data.replace('Array',''));
        				console.log("打印",pic)
                        if (pic.status == 200) {
                            that.setData({
                                addedCount: count,
                                img: pic.data
                            });
                            uni.hideLoading({});
                        } else {
                            uni.showToast({
                                title: pic.msg,
                                icon: 'none'
                            });
                        }
                    }
                });
            // }
        },

        priceFun(e) {
            this.setData({
                price: e.detail.value
            });
        },

        textarea(e) {
            var value = e.detail.value.replace(/\s+/g, '');
            this.setData({
                word_num: value.length,
                word_left: 20 - value.length,
                name: value
            });
        },

        submit(e) {
            console.log( parseInt(this.stock));
            if (!( parseInt(this.stock)>0)) {
                this.tips.tips("库存无效！")

                return false;
            }
            if (!this.name) {
                app.globalData.util.message('请输入名称', '', 'error');
                return false;
            }

            if (this.price <= 0) {
                app.globalData.util.message('请输入价格', '', 'error');
                return false;
            }

            if (!this.cate_id) {
                app.globalData.util.message('请选择分类', '', 'error');
                return false;
            }
          

           
            if (!this.img) {
                app.globalData.util.message('请上传图片', '', 'error');
                return false;
            }
            let specs=JSON.stringify({
                name:this.specsName,
                list:this.specs
            })
            let attribute=JSON.stringify({
                name:this.attributeName,
                list:this.attribute
            })
            if (this.specs.length==0) {
                specs=""
            }

            if (this.attribute.length==0) {
                attribute=""
            }

             
			if(!this.id){
				app.globalData.util.request({
				    url: 'ZhGoods/add',
				    data: {
				        goods_img: this.img,
				        goods_name: this.name,
				        price: this.price,
				        goods_type_id: this.cate_id,
				        s_id: uni.getStorageSync('schoolId'),
				        status: e.currentTarget.dataset.status,
                        specs,
                        attribute,
                        stock: this.stock,
                        quota: this.quota,
                        specs_list: JSON.stringify(this.specs_list)

				    },
				
				    success(res) {
				        if (res.data.status == 200) {
				            uni.showToast({
				                title: res.data.message
				            });
				            setTimeout(function () {
				                uni.redirectTo({
				                    url: '/gc_school/pages/shop/goods'
				                });
				            }, 1000);
				        }
				    }
				},true);
			}else {
				app.globalData.util.request({
				    url: 'ZhGoods/update',
				    data: {
				        goods_img: this.img,
				        goods_name: this.name,
				        price: this.price,
				        goods_type_id: this.cate_id,
				        s_id: uni.getStorageSync('schoolId'),
				        status: e.currentTarget.dataset.status,
						id: this.id,
                        specs,
                        attribute,
                        stock: this.stock,
                        quota: this.quota,
                        specs_list: JSON.stringify(this.specs_list),

                        // specs_list: JSON.stringify(
                        //     [
                        //         { 
                        //             "name": "饮品", 
                        //             "list": [
                        //                 { "type": "可乐", "price": "4.00" }, 
                        //                 { "type": "加奶", "price": "5.00" },
                        //                 { "type": "冰峰", "price": "4.00" }
                        //             ] 
                        //         }, 
                        //         { 
                        //             "name": "加料", 
                        //             "list": [
                        //                 { "type": "加粉", "price": "5.00" }, 
                        //                 { "type": "加蘑菇", "price": "3.00" },
                        //                 { "type": "加鸡腿", "price": "6.00" }
                        //             ] 
                        //         },
                        //         {
                        //             "name": "打包方式(必选，不选下单无效)",
                        //             "list": [
                        //                 { "type": "塑料袋袋", "price": "0.00" },
                        //                 { "type": "打包盒(中)", "price": "2.00" },
                        //                 { "type": "打包盒(豪华)", "price": "6.00" }
                        //             ]
                        //         }
                        //     ]
                        // )
                        
                        
                        
                        

				    },
				
				    success(res) {
				        if (res.data.status == 200) {
				            uni.showToast({
				                title: res.data.message
				            });
				            setTimeout(function () {
				                uni.redirectTo({
				                    url: '/gc_school/pages/shop/goods'
				                });
				            }, 1000);
				        }
				    }
				},true);
			}

            
        }
    }
};
</script>
<style>
/* gc_school/pages/shop/addgoods.wxss */
page {
    background: #f9f9f9;
}
.box {
    background: white;
    border-radius: 10rpx;
    margin: 30rpx;
    padding: 30rpx;
}
.textarea {
    background: #f9f9f9;
    border-radius: 10rpx;
    width: 100%;
    height: 150rpx;
    margin-top: 20rpx;
    padding: 20rpx;
}
.left_num {
    position: absolute;
    right: 20rpx;
    bottom: 20rpx;
    color: #d1d1d1;
}
.size30 {
    font-size: 30rpx;
}
.name_input {
    width: 50%;
}
.img {
    margin-top: 30rpx;
    width: 200rpx;
    height: 200rpx;
}
.btn_row {
    margin: 70rpx 50rpx 30rpx;
}
.btn_:first-child {
    background: #00bb69 !important;
}
.btn_ {
    width: 300rpx;
    height: 80rpx;
    line-height: 80rpx;
    background: #ff6344;
    color: white;
    text-align: center;
    border-radius: 10rpx;
    font-size: 30rpx;
}
</style>
<style lang="scss">
    @import "./addgoods.scss";
</style>
